﻿using AutoMapper;
using B.S.BasicData.API.Write.Application.Command.Role;
using B.S.BasicData.Domain.Entities.UserRoleMenu;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Transactions;

namespace B.S.BasicData.API.Write.Application.Handler.Role
{
    /// <summary>
    /// 为用户分配角色请求命令处理类
    /// </summary>
    public class CreateUserRoleHandler : IRequestHandler<CreateUserRoleCommand, ApiResult<int>>
    {
        IBaseRepository<UserRoleModel> userRoleRep;

        public CreateUserRoleHandler(IBaseRepository<UserRoleModel> userRoleRep)
        {
            this.userRoleRep = userRoleRep;
        }

        public Task<ApiResult<int>> Handle(CreateUserRoleCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();

                var userrole=userRoleRep.GetAll().Where(x=>x.RoleId==request.roleId).ToList();
                foreach (var item in userrole)
                {
                    item.IsDeleted = true;
                }


                var userroles=new List<UserRoleModel>();

                foreach (var item in request.userId)
                {
                    userroles.Add(new UserRoleModel()
                    {
                        RoleId = request.roleId,
                        UserId = item
                    });

                }
                int r1 = 0;
                int r = 0;

                using(TransactionScope tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    if(userrole.Count()>0)
                    {
                        r= userRoleRep.UpdateAsync(userrole).Result;
                    }
                    if(userroles.Count()>0)
                    {
                        r1=userRoleRep.CreateAsync(userroles).Result;
                    }
                    tran.Complete();
                }

                if (r1 > 0)
                {
                    res.Msg = "角色分配成功";
                    res.Data = r1;
                    res.Code = ApiEnum.Success;
                }
                else
                {
                    res.Msg = "角色分配失败";
                    res.Code = ApiEnum.Fail;
                }

                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
